#!/usr/bin/env python3
# run.py

import uvicorn
import subprocess
import sys
import os
import signal
import time
from multiprocessing import Process
from config.settings import settings
from config.celery_config import CeleryConfig

def start_celery_worker():
    """启动Celery worker进程"""
    try:
        print("启动Celery worker...")
        # 启动Celery worker
        subprocess.run([
            sys.executable, "-m", "celery", 
            "-A", "tasks.celery_app:celery_app", 
            "worker", 
            "--loglevel=info",
            "--concurrency=2",
            "--queues=file_processing,vector_processing,batch_processing,default"
        ], check=True)
    except subprocess.CalledProcessError as e:
        print(f"Celery worker启动失败: {e}")
    except KeyboardInterrupt:
        print("Celery worker被中断")

def start_flower_monitor():
    """启动Flower监控界面"""
    try:
        print("启动Flower监控界面...")
        subprocess.run([
            sys.executable, "-m", "celery", 
            "-A", "tasks.celery_app:celery_app", 
            "flower",
            f"--port={CeleryConfig.FLOWER_PORT}",
            f"--address={CeleryConfig.FLOWER_HOST}"
        ], check=True)
    except subprocess.CalledProcessError as e:
        print(f"Flower监控启动失败: {e}")
    except KeyboardInterrupt:
        print("Flower监控被中断")

def start_api_server():
    """启动API服务器"""
    try:
        print(f"启动API服务器...")
        uvicorn.run(
            "app.main:app",
            host=settings.API_HOST,
            port=settings.UPLOAD_API_PORT,
            reload=settings.DEBUG,
            log_level=settings.LOG_LEVEL.lower()
        )
    except KeyboardInterrupt:
        print("API服务器被中断")

def signal_handler(signum, frame):
    """信号处理器"""
    print("\n正在关闭服务...")
    sys.exit(0)

if __name__ == "__main__":
    # 注册信号处理器
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    print(f"启动 {settings.PROJECT_NAME} v{settings.VERSION}")
    print(f"API文档: http://{settings.API_HOST}:{settings.UPLOAD_API_PORT}/docs")
    print(f"健康检查: http://{settings.API_HOST}:{settings.UPLOAD_API_PORT}/api/v1/health")
    print(f"Flower监控: http://{CeleryConfig.FLOWER_HOST}:{CeleryConfig.FLOWER_PORT}")
    print(f"Redis连接: {CeleryConfig.BROKER_URL}")
    
    # 检查命令行参数
    if len(sys.argv) > 1:
        mode = sys.argv[1].lower()
        
        if mode == "api":
            # 仅启动API服务器
            start_api_server()
        elif mode == "worker":
            # 仅启动Celery worker
            start_celery_worker()
        elif mode == "flower":
            # 仅启动Flower监控
            start_flower_monitor()
        elif mode == "all":
            # 启动所有服务（多进程）
            print("启动所有服务...")
            
            # 启动Celery worker进程
            worker_process = Process(target=start_celery_worker)
            worker_process.start()
            
            # 启动Flower监控进程
            flower_process = Process(target=start_flower_monitor)
            flower_process.start()
            
            # 等待一下让worker启动
            time.sleep(3)
            
            # 启动API服务器（主进程）
            try:
                start_api_server()
            finally:
                # 清理子进程
                worker_process.terminate()
                flower_process.terminate()
                worker_process.join()
                flower_process.join()
        else:
            print("使用方法:")
            print("  python run.py          # 启动API服务器")
            print("  python run.py api      # 仅启动API服务器")
            print("  python run.py worker   # 仅启动Celery worker")
            print("  python run.py flower   # 仅启动Flower监控")
            print("  python run.py all      # 启动所有服务")
            sys.exit(1)
    else:
        # 默认启动API服务器
        start_api_server() 